package com.qianchang.microfinance.view.home.cash;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.DMLog;
import com.dm.library.utils.FileUtils;
import com.dm.library.utils.FormatUtil;
import com.dm.library.utils.ToastUtil;
import com.dm.library.widgets.element.DButton;
import com.dm.library.widgets.element.DTextView;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.HSUploadFileBean;
import com.qianchang.microfinance.bean.LoanProgBean;
import com.qianchang.microfinance.bean.LoanType;
import com.qianchang.microfinance.bean.ProjectStatus;
import com.qianchang.microfinance.bean.SubmitLoanBean;
import com.qianchang.microfinance.bean.UploadFileBean;
import com.qianchang.microfinance.bean.UserLoginInfo;
import com.qianchang.microfinance.bean.event.AgreementEvent;
import com.qianchang.microfinance.global.ConstantAppInfo;
import com.qianchang.microfinance.global.DMApplication;
import com.qianchang.microfinance.setting.SettingTradPasswordActivity;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.utils.SpanUtils;
import com.qianchang.microfinance.view.MainActivity;
import com.qianchang.microfinance.view.base.BaseActivity;
import com.qianchang.microfinance.view.dialog.alert.DimengConfirmAlertDialog;
import com.qianchang.microfinance.view.dialog.alert.DimengSingleButtonAlertDialog;
import com.qianchang.microfinance.view.mine.loan.ConfirmAgreementActivity;
import com.qianchang.microfinance.view.mine.loan.HSLoanWithdrawActivity;
import com.qianchang.microfinance.view.mine.loan.LoanProgressActivity;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.tsign.esign.tsignsdk2.TESeal;
import cn.tsign.esign.tsignsdk2.custom.Custom;
import cn.tsign.esign.tsignsdk2.custom.DialogCustom;
import cn.tsign.esign.tsignsdk2.enums.EnumTipMsgGravity;
import cn.tsign.esign.tsignsdk2.enums.EnumWindow;
import cn.tsign.esign.tsignsdk2.util.extend.Callback;
import cn.tsign.network.enums.EnumHandSignColor;

public class ApplyProgressActivity extends BaseActivity {

    @BindView(R.id.imageView)
    ImageView imageView;
    @BindView(R.id.tv_status)
    DTextView tvStatus;
    @BindView(R.id.tv_amount)
    DTextView tvAmount;
    @BindView(R.id.btn_finish)
    DButton btnFinish;
    @BindView(R.id.tv_back)
    DTextView tvback;

    private String status;
    private double applyAmount;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply_progress);
        ButterKnife.bind(this);
        initView();
        initData();
        setCustomStyle();       //2018.1.16鸿胜科技新增
        getSignAccountId();
    }

    @Override
    protected void initView() {
        super.initView();
        tvback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(MainActivity.class, true);
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        Bundle bundle = getBundle();
        if (bundle != null) {
            //显示借款进度
            setTitleName(getString(R.string.title_loan_proress));
            applyAmount = bundle.getDouble("applyAmount");

            tvStatus.setTextContent(getString(R.string.apply_loan));
            tvAmount.setTextContent("¥" + FormatUtil.numKbPointFormat(applyAmount));
            imageView.setBackgroundResource(R.drawable.img_money);
            btnFinish.setText("确认申请");
        }
    }

    @OnClick(R.id.btn_finish)
    public void onViewClicked() {
        DimengConfirmAlertDialog confirmAlertDialog = DimengConfirmAlertDialog.newInstance("借款确认", "是否本人同意借款");
        confirmAlertDialog.setOnDialogClickListener(new DimengConfirmAlertDialog.OnDialogClickListener() {
            @Override
            public void agree() {
                checkAgreement();
            }

            @Override
            public void cancel() {

            }
        });
        confirmAlertDialog.show(getSupportFragmentManager(), getClass().getSimpleName());
    }

    /**
     * 2018.1.16鸿胜科技新增
     */
    private String accountId;
    private static final String TAG = "ConfirmAgreement";

    // 对SDK里的页面做一些样式设置
    private void setCustomStyle() {
        //对SDK做个性化设置
        Custom custom = new Custom();
        //设置标题的背景颜色
        custom.setTitleBackgroundColor(R.color.black);
        //设置标题的文字颜色
        custom.setTitleTextColor(R.color.red);
        //设置标题文本
        custom.setTitleText(R.string.Label_sure_agreement);
        //设置手绘签名前的提示语
        custom.setTipMsg("请签名");
        //设置提示语对齐方向
        custom.setTipMsgGravity(EnumTipMsgGravity.center);
        //设置手绘的签署提供的颜色,只能是红,黑,蓝
        custom.getHandColor().add(EnumHandSignColor.Blue);
        custom.getHandColor().add(EnumHandSignColor.Black);
        custom.getHandColor().add(EnumHandSignColor.Red);

        //快捷签弹出式对话框的样式
        DialogCustom dialogCustom = new DialogCustom();
        dialogCustom.setCancelResourceId(R.drawable.tsign_quick_sign_dialog_cancel);
        dialogCustom.setFullScreenResourceId(R.drawable.tsign_quick_sign_dialog_full_screen);
        dialogCustom.setClearResourceId(R.drawable.tsign_quick_sign_dialog_clear);
        dialogCustom.setConfirmResourceId(R.drawable.tsign_quick_sign_dialog_confirm);
        custom.setDialogCustom(dialogCustom);

        TESeal.getInstance().setmCustom(custom);
    }


    private void getSignAccountId() {

        UserLoginInfo userLoginInfo = DMApplication.getInstance().getmUserLoginInfo();
        String usid = userLoginInfo.getUserId();
        HttpParams params = new HttpParams();
        params.put("userId",usid);

        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.ES_CREATEAGREE, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(JsonResult<String> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    DMLog.e(TAG, "onSuccess: " + response.getObject());
                    accountId = response.getObject();
                } else {
                    ToastUtil.getInstant().show(ApplyProgressActivity.this, response.getDescription());
                }
            }


            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(ApplyProgressActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
            }
        });
    }

    /**
     * 确认合同
     */
    private void checkAgreement() {
        show();
        TESeal.getInstance().quickToSign(ApplyProgressActivity.this, accountId, EnumWindow.Dialog, new Callback() {

            @Override
            public void didSignBackImage(String id, String sealImagePath) {
                dismiss();
                hsuploadFile(sealImagePath);
            }

            @Override
            public void onError(JSONObject json) {
                dismiss();
                ToastUtil.getInstant().show(ApplyProgressActivity.this, json.toString());
            }

            @Override
            public void onCancel(JSONObject json) {
                dismiss();
            }
        });
    }

    private void loanCash() {
        show();
        HttpParams params = new HttpParams();
        Bundle bundle = getBundle();
        params.put("applyAmount", bundle.getDouble("applyAmount"));//借款金额
        params.put("deadlinekey", bundle.getString("deadlinekey"));//借款期限
        params.put("deadline", bundle.getInt("deadline")+"");//
        params.put("unit", bundle.getString("unit"));
        params.put("productType", bundle.getString("productType"));
        params.put("productId", bundle.getString("productId"));
        params.put("repaymentType", bundle.getString("repaymentType"));
        params.put("serviceFeeRate", bundle.getDouble("serviceFeeRate"));//借款周期
        params.put("lastProductUpdateTime", bundle.getString("lastProductUpdateTime"));
        params.put("gradeId", bundle.getString("gradeId"));
        params.put("daysPerMonth", bundle.getInt("daysPerMonth"));//日利率
        params.put("serviceFeeSetting", bundle.getString("serviceFeeSetting"));
        params.put("purpose",bundle.getInt("purpose"));

        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.PROJECT_INSERT, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(JsonResult<String> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    String projectId = response.getObject();
                    if (null != projectId) {
                        Bundle bundle = new Bundle();
                        bundle.putString("projectId",projectId);
                        startActivity(ApplySuccessActivity.class,bundle);
                    }else{
                        ToastUtil.getInstant().show(ApplyProgressActivity.this, "申请失败");
                    }
                } else {
                    ToastUtil.getInstant().show(ApplyProgressActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();

                ToastUtil.getInstant().show(ApplyProgressActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }

    /**
     * 只有单个文件才支持上传
     *
     * @param imagePath 文件路径
     */
    public void hsuploadFile(final String imagePath) {
        if (null == imagePath) {
            return;
        }
        UserLoginInfo userLoginInfo = DMApplication.getInstance().getmUserLoginInfo();
        String usid = userLoginInfo.getUserId();

        File file = new File(imagePath);
        Map<String, File> files = new HashMap<>();
        files.put(file.getName(), file);
        Map<String, String> fileParamsMap = new HashMap<>();
        fileParamsMap.put("allowFile", "jpg,png");
        fileParamsMap.put("fileType", "0");
        fileParamsMap.put("isTransform", "false");
        fileParamsMap.put("userId",usid);
        fileParamsMap.put("projectId","123");

        show();
        DMOKHttpUtils.getInstance().uploadFile(this, DMConstant.ApiURL.WFILE_UPLOAD, fileParamsMap, "uploadFile", files, new RequestCallBack<HSUploadFileBean>() {
            @Override
            public void onSuccess(JsonResult<HSUploadFileBean> response) {

                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    HSUploadFileBean uploadFileBean = response.getObject();
                    loanCash();//提交借款申请
                } else {
                    dismiss();
                    ToastUtil.getInstant().show(ApplyProgressActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(ApplyProgressActivity.this.getApplicationContext(), msg);
            }

            @Override
            public void onConnectFailure(String msg) {
                dismiss();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 100 && resultCode == -1){             //如果从这里跳转至合同页面点击合同确认提交借款返回这里的时候结束页面
            ApplyProgressActivity.this.finish();
        }
    }
}
